package at.horario.web;

import at.horario.model.User;
import at.horario.model.Role;
import at.horario.web.pages.Index;
import at.horario.web.pages.Logout;
import at.horario.Constants;
import org.apache.wicket.Request;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.authorization.strategies.role.Roles;
import org.apache.wicket.authentication.AuthenticatedWebSession;
import org.apache.wicket.authentication.AuthenticatedWebApplication;

import java.util.Locale;


public class HorarioSession extends AuthenticatedWebSession {
    private User user;
    AuthenticatedWebApplication d;
    private static final String ADMIN = "admin";

    /**
     * Construct.
     *
     * @param application The web application
     * @param request     The current request object
     */
    public HorarioSession(AuthenticatedWebApplication application, Request request) {
        super(application, request);
        setLocale(new Locale("pt", "PT"));
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }


    public boolean authenticate(String username, String password) {
        boolean s = ADMIN.equalsIgnoreCase(username) && ADMIN.equalsIgnoreCase(password);
        if (s){
            user = new User(username);
            user.addRole(new Role("user"));
            user.addRole(new Role("admin"));
        }

        return s;

    }

    @Override
    public Roles getRoles() {
        Roles roles = new Roles();

        if (isSignedIn()){
            roles.add("user");
            for (Role role : user.getRoles())
                roles.add(role.getName());

            roles.add(Logout.class.getSimpleName().toLowerCase());
            roles.add(Index.class.getSimpleName().toLowerCase());
        }

        return roles;
    }

    public boolean contem(Class<? extends WebPage> pageClass) {
        return contem(pageClass.getSimpleName().toLowerCase());
    }

    public boolean contem(String role) {
        return getRoles().contains(role) || isAdmin();
    }

    private boolean isAdmin() {
        return getRoles().contains(Constants.ADMIN_ROLE);
    }


    
}
